using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;

namespace DaprPlus.Extensions
{
    public static class ProcessExtensions
    {
        /// <summary>
        /// 【仅支持Windows】获取一个正在运行的进程的命令行参数。
        /// 与<see cref="M:System.Environment.GetCommandLineArgs" />一样，使用此方法获取的参数是包含应用程序启动时的参数
        /// </summary>
        /// <param name="process">一个正在运行的进程</param>
        /// <returns>表示应用程序运行命令行参数的字符串</returns>
        [SupportedOSPlatform("windows")]
        public static string GetCommandLineArgs(this Process process)
        {
            Check.NotNull<Process>(process, nameof(process));
            try
            {
                return GetCommandLineArgsCore();
            }
            catch (Win32Exception ex) when (ex.ErrorCode == -2147467259)
            {
                return string.Empty;
            }
            catch (InvalidOperationException)
            {
                return string.Empty;
            }

            string GetCommandLineArgsCore()
            {
                using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id.ToString()))
                {
                    using (ManagementObjectCollection source = managementObjectSearcher.Get())
                        return source.Cast<ManagementBaseObject>().SingleOrDefault<ManagementBaseObject>()?["CommandLine"].ToString() ?? "";
                }
            }
        }
    }
}
